package zl.jmail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author  SuperZL 
 * @version 2012-9-3 上午10:37:16
 * 邮件发送类
 */
public class SimpleMailSender {
	
	/**
	 * @param sendInfo
	 * @return
	 * 发送指定邮件信息
	 */
	public boolean sendTextMail(MailSendInfo sendInfo){
		MyAuthenticator myAuthenticator = null;		//自定义类继承自信息验证类
		Properties properties = sendInfo.getProperties();	//所发邮件的信息
		if(sendInfo.isValidate())	//判断是否需要验证信息
			//邮件信息里的用户名密码实例化验证信息类
			myAuthenticator = new MyAuthenticator(sendInfo.getUsername(), sendInfo.getPassword());
		//根据邮件信息和验证信息实例化Session对象
		Session session = Session.getInstance(properties,myAuthenticator);
		try{
			//根据Session对象得到Message对象
			Message mailMessage = new MimeMessage(session);
			//根据发送邮件信息设置Message对象的特定属性
			Address from = new InternetAddress(sendInfo.getFromAddress());
			mailMessage.setFrom(from);
			Address to = new InternetAddress(sendInfo.getToAddress());
			mailMessage.setRecipient(Message.RecipientType.TO,to);
			//设置邮件主题
			mailMessage.setSubject(sendInfo.getSubject());
			//设置邮件发送日期
			mailMessage.setSentDate(new Date());
			String mailContent = sendInfo.getContent();
			//设置邮件发送内容
			mailMessage.setText(mailContent);
			mailMessage.setFileName("C:\\Users\\SuperZL\\Desktop\\新建文本文档.txt");
			//发送邮件
			Transport.send(mailMessage);
			//如无异常。则发送成功
			return true;
		}catch(MessagingException e){
			e.printStackTrace();
		}
		return false;
	}
}
